# -- encoding:utf-8 --

from flask import Flask, request, jsonify  # pip install flask
import pickle
import re
import tensorflow as tf
from model import Model
from utils import get_logger
from utils import load_config
from data_utils import input_from_line

flags = tf.app.flags
flags.DEFINE_string("log_file", "./log/train.log", "File for log")
flags.DEFINE_string("map_file", "./config/maps.pkl", "file for maps")
flags.DEFINE_string("ckpt_path", "./ckpt/bilstm", "Path to save model")
flags.DEFINE_string("config_file", "./config/config_file", "File for config")
FLAGS = tf.app.flags.FLAGS

# 日志工具(记录操作日志)
logger = get_logger(FLAGS.log_file)

def predict(line):
    config = load_config(FLAGS.config_file)
    tf_config = tf.ConfigProto()
    tf_config.allow_soft_placement = True
    tf_config.gpu_options.allow_growth = True
    with open(FLAGS.map_file, "rb") as f:
        char_to_id, id_to_char, tag_to_id, id_to_tag = pickle.load(f)
    with tf.Session(config=tf_config) as sess:
        model = Model(config)
        # 模型恢复
        sess.run(tf.global_variables_initializer())
        ckpt = tf.train.get_checkpoint_state(FLAGS.ckpt_path)
        if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
            model.saver.restore(sess, ckpt.model_checkpoint_path)
            if line.strip():
                line = re.compile(' ').sub('', line)  # 去掉中间空格
                result = model.evaluate_line(sess, input_from_line(line, char_to_id), id_to_tag)
                return result
            else:
                return 4001

# Web API构建
app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def get_text_input():
    text = request.args.get('inputStr', None)
    logger.info("Accept request parameters 【inputStr=%s】" % text)
    if text:
        data = predict(text)
        print(data)
        return jsonify({
            "code": 200,
            "msg": "successful!!!",
            "data": data
        })
    else:
        return jsonify({
            "code": 0,
            "msg": "Fail, No request parameters<inputStr>!!!"
        })

if __name__ == "__main__":
    # 设置json返回的中文不进行编码
    app.config['JSON_AS_ASCII'] = False
    app.run(host='127.0.0.1', port=5003)
